//
//  HomeController.swift
//  eBooks
//
//  Created by JunMing on 2019/10/11.
//  Copyright © 2019 赵俊明. All rights reserved.
//

import UIKit
import RxCocoa
import RxSwift
import SnapKit

class HomeController: EbookBaseController,AdMobViewProtocol {
    private lazy var bag = DisposeBag()
    @IBOutlet weak var rightItem: UIBarButtonItem!
    @IBOutlet weak var leftItem: UIBarButtonItem!
    private var colView: UICollectionView!
    private let vModel = ViewModel()
    private let layout = HomeFlowLayout()
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        reloadDatas()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        setupViews()
        tableViewEvent()
        registActionEvent()
        
        if !Tools.getVip() {
            loadAdMobView(rootVC:self)
        }
        
        if Tools.showYinSi() {
            let sheetItem = SheetItem(title: "感谢您信任并使用追书阅读器！本服务需联网，申请通知权限用于为您提供数据更新，优惠活动等信息服务，点击同意即表示您同意上述服务，感谢您信任并使用追书阅读器！本服务需联网，申请通知权限用于为您提供数据更新，优惠活动等信息服务，点击同意即表示您同意上述服务,以及《隐私政策》、《服务协议》。")
            sheetItem.className = "BookYinSiAlert"
            sheetItem.sheetType = .yinsi
            let sheetManager = SheetManager(superView: nil, item: sheetItem)
            sheetManager.update()
        }
    }
    
    func setupViews() {
        colView = UICollectionView(frame: view.bounds, collectionViewLayout: layout)
        colView.register(HomeCollectionCell.self, forCellWithReuseIdentifier: "homeCell")
        colView.backgroundColor = UIColor.randColor
        switchCell()
        colView.backgroundColor = UIColor.white
        colView.showsVerticalScrollIndicator = false
        colView.alwaysBounceVertical = true
        // 取消设置代理
        // colView.rx.setDelegate(self).disposed(by: bag)
        view.addSubview(colView)
        colView.snp.makeConstraints { (make) in
            make.top.bottom.width.equalTo(view);
        }
        
        rightItem.rx.tap.subscribe(onNext: { [weak self] in
            MobClick.event("home_search")
            self?.navigationController?.pushViewController(SearchController(), animated: true)
            //self?.loadAdMobView(rootVC:self!)
        }).disposed(by: bag)
        
        leftItem.rx.tap.subscribe(onNext: { [weak self] in
            let navController = NavController(rootViewController: SettingController())
            navController.modalPresentationStyle = .fullScreen
            self?.present(navController, animated: true, completion: nil)
        }).disposed(by: bag)
    }
    
    func switchCell() {
        if Tools.getVertical() {
            let margin:CGFloat = 20
            let count:CGFloat = 3
            let w = (view.width - (count+1)*margin)/count
            let h = w*1.9
            layout.minimumLineSpacing = 20
            layout.itemSize = CGSize(width: w, height: h)
            layout.sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: margin, right: margin)
        }else{
            layout.minimumLineSpacing = 6
            layout.itemSize = CGSize(width: colView.width, height: 84)
            layout.sectionInset = UIEdgeInsets(top: 10, left: 0, bottom: 20, right: 0)
        }
    }
    
    func tableViewEvent() {
        vModel.modelObserable.asObservable().bind(to: colView.rx.items(cellIdentifier:"homeCell",cellType: HomeCollectionCell.self)) { row,model,cell in
            cell.model = model
            cell.switchVerticalHorizontal()
            cell.touchCellBlock = { [weak self] model, share in
                if share {
                    self?.loadAlertView(model,row)
                    print(model.title() as Any)
                    MobClick.event("home_cell_more")
                }else{
                    model.isSave = !model.isSave;
                    SQLHelper.share.updateLocalDB(model, type: .issave)
                    let indexPath = IndexPath(item: row, section: 0)
                    self?.colView.reloadItems(at: [indexPath])
                    print(model.title() as Any)
                    MobClick.event("home_cell_save")
                }
            }
            }.disposed(by: bag)
        
        // 点击
        colView.rx.itemSelected.subscribe(onNext: { [weak self] (indexPath) in
            print(indexPath.row)
            let model = self?.vModel.modelObserable.value[indexPath.row]
            self?.openEpubBooks(model!)
        }).disposed(by: bag)
    }
    
    func reloadDatas()  {
        for model in SQLHelper.share.fetchLocalDB(queryType: .deleteFalse) {
            if !isExistModel(model) {
                vModel.modelObserable.value.append(model)
            }
        }
        colView.reloadData()
    }
    
    func isExistModel(_ model:Model) -> Bool {
        for item in vModel.modelObserable.value {
            if model.bookurl() == item.bookurl() {
                return true
            }
        }
        return false
    }
    
    func loadAlertView(_ model:Model,_ row:Int) {
        
        let name = AlertItem(title: model.fullTitle()!, icon: nil)
        name.textColor = UIColor.colorFromHexString("#4876FF")
        name.font = UIFont.medium(18)
        name.eventName = kSheetBookNameEventName
        
        let upload = AlertItem(title: "面对面传书", icon: nil)
        upload.icon = UIImage.imageNamed(bundleName: "supervip")
        upload.textColor = UIColor.colorFromHexString("#EE9A00")
        upload.font = UIFont.medium(15)
        upload.eventName = kSheetWifiEventName
        
        let delete = AlertItem(title: "⁉️删除", icon: nil)
        delete.textColor = UIColor.colorFromHexString("#FF4500")
        delete.font = UIFont.medium(15)
        delete.eventName = kSheetDeleteEventName
        
        let switchCell = AlertItem(title: "切换书架", icon: nil)
        switchCell.textColor =  UIColor.colorFromHexString("#EE9A00")
        switchCell.font = UIFont.medium(15)
        switchCell.eventName = "kSheetSwitchEventName"
        
        let sheetItem = SheetItem(title: "")
        sheetItem.className = "BookInfoContent"
        if Tools.getVip() {
            sheetItem.models = [name,switchCell,upload,delete]
        }else{
//            let buyVip = AlertItem(title: "⭐️购买VIP", icon: nil)
//            buyVip.textColor = UIColor.colorFromHexString("#EE9A00")
//            buyVip.font = UIFont.medium(15)
//            buyVip.eventName = kEbooksBuyVipEventName
            
            let admob = AlertItem(title: model.fullTitle()!, icon: nil)
            admob.rootVc = self
            sheetItem.models = [admob,name,switchCell,upload,delete]
        }
        
        let sheetManager = SheetManager(superView: view, item: sheetItem)
        sheetItem.sheetType = .bottom
        sheetManager.update()
        
        registerEvent(eventName: kSheetBookNameEventName, block: { [weak self] item in
            let indexPath = IndexPath(item: row, section: 0)
            let model = self?.vModel.modelObserable.value[indexPath.row]
            self?.openEpubBooks(model!)
            MobClick.event("home_alert_open")
        }, next: false)
        
        registerEvent(eventName: kSheetWifiEventName, block: { [weak self] item in
            MobClick.event("home_alert_wifi")
            var ip = "http://192.168.0.10"
            if let nIP = Tools.getIP() { ip = nIP }
            self?.showAlert(model.title(), "请在👇输入对方地址", ip, handler: { text in
                if let urlStr = text {
                    self?.title = "正在发送" + model.fullTitle()!
                    NetWorkSession.epub(urlStr, filePath: model.localPath(), fileName: model.fullTitle()!) { status, response, desc in
                        if status { Tools.setIP(urlStr) }
                        DispatchQueue.main.async(execute: {
                            self?.title = status ? "发送成功🐶！" : "发送失败😭"
                            let deadLine = DispatchTime.now()+1
                            DispatchQueue.main.asyncAfter(deadline: deadLine, execute: {
                                self?.title = "我的书架"
                                if Tools.showGuide(status) {
                                    self?.showGuideVideo()
                                }
                            })
                        })

                        print(response as Any)
                    }
                }
            })
            
        }, next: false)
        
        registerEvent(eventName: kSheetDeleteEventName, block: { item in
            MobClick.event("luanch_jump_buy_vip")
            self.vModel.modelObserable.value.remove(at: row)
            self.colView.reloadData()
            FileHelper.deleteFile(model.fullname)
            model.isdel = true
            SQLHelper.share.updateLocalDB(model, type: .isDel)
        }, next: false)
    }
    
    // 展示指导视频
    func showGuideVideo() {
        let left = AlertItem(title: "确定", icon: nil)
        let right = AlertItem(title: "取消", icon: nil)
        let item = SheetItem(title: "遇到问题？")
        item.subTitle = "点击确定按钮观看Wi-Fi面对面传书指导视频"
        item.className = "BookInfoAlert"
        item.models = [left,right]
        let manager = SheetManager(superView: view, item: item)
        item.sheetType = .right
        manager.update()
        left.action = { [weak self] _ in
            let avVC = AvKitController()
            avVC.modalPresentationStyle = .fullScreen
            self?.present(avVC, animated: true, completion: nil)
            avVC.urlVideo = "http://www.restcy.com/source/guide_02.mp4";
        }
    }
    
    func registActionEvent() {
        
        registerEvent(eventName: "kSheetSwitchEventName", block: { [weak self] model in
            Tools.switchVertical()
            self?.switchCell()
            self?.colView.reloadData()
        }, next: false)
        
        registerEvent(eventName: kShareEventName, block: { model in
            
        }, next: false)
        
        // 展示购买Vip
        registerEvent(eventName: kEbooksBuyVipEventName, block: { [weak self] item in
            // self?.buyAction(self?.view)
            self?.createRewardAD()
            MobClick.event("home_alert_buy_vip")
        }, next: false)
    }
    
    // MARK: -- 重写方法
    override func changeDataSource(_ model:Model,_ delete:Bool = false) {
        if delete {
            var findIndex:Int?
            for (index,item) in vModel.modelObserable.value.enumerated() {
                if item.fullname == model.fullname {
                    findIndex = index
                    break
                }
            }
            
            if let index = findIndex {
                vModel.modelObserable.value.remove(at: index)
            }
        }else {
            vModel.modelObserable.value.append(model)
        }
    }
}

